'use strict'
var express = require('express');
var router = express.Router();
var cors = require('cors');
router.use(cors());
const User = require('../models/models').user;
const send_sms = require('../modules/send_sms');
const md5 = require('md5');
const jwt = require('jsonwebtoken');
const fs = require('fs');
const session = require('express-session');
const sess = session({
    cookie: 60 * 10000000,
    secret: '?ccmsshowsecrete?',
    resave: true,
    saveUninitialized: true
});
var path = require('path');
const isTest = true;
const countryCode = '65';
// GET route for reading data
router.get('/', function (req, res, next) {
    return res.sendFile(path.join(__dirname + '/templateLogReg/index.html'));
});

//POST route for updating data
/**
 * ticketType == 0: TT
 * ticketType == 1: SRQ
 * ticketType == 2: read only
 * ticketType == 3: Ticket confirmed
 */
router.post('/getTicket', function (req, res, next) {
    let token = req.body.token;
    let ticketType = req.body.ticketType;
    let write = req.body.write;
    if (token != ",W4HDZJbxP8S)H<-")
        return res.json({
            errorCode: 1,
            message: 'wrong credential'
        })
    const rawdata = fs.readFileSync('tickets.json');
    let _ticket = JSON.parse(rawdata);
    let curDate = new Date(_ticket.timestamp);
    // let _d = d.getDate();
    let _today = new Date(Date.now());
    // let _dateChanged = _today.getDate() > (curDate).getDate();
    // let newNum = 1, preNum=0;
    if (_today.getDate() > (curDate).getDate()) {
        _ticket.TT = 1;
        _ticket.SRQ = 1;
    }
    let retVal = {
        errorCode: 0,
        curTTNumber: _ticket.TTNumber,
        curSRQNumber: _ticket.SRQNumber,
        newTTNumber: _ticket.TTNumber,
        newSRQNumber: _ticket.SRQNumber,
        timestamp: Date.now()
    }
    if (ticketType == 0) {
        _ticket.TTNumber++;
        retVal.newTTNumber = _ticket.TTNumber;
    } else if (ticketType == 1) {
        _ticket.SRQNumber++;
        retVal.newSRQNumber = _ticket.SRQNumber;
    } else {
        retVal.newTTNumber++;
        retVal.newSRQNumber++;
    }
    if (write == "true" && (ticketType == 0 || ticketType == 1)) {
        fs.writeFile('tickets.json', JSON.stringify(_ticket), err => {
            if (err) console.error(err)
        })
    }

    return res.json(retVal)
})

router.post('/signup', function (req, res, next) {
    // confirm that user typed same password twice
    if (req.body.password !== req.body.passwordConf) {
        var err = new Error('Passwords do not match.');
        err.status = 400;
        res.send("passwords dont match");
        return next(err);
    }

    if (req.body.email &&
        req.body.username &&
        req.body.password &&
        req.body.passwordConf) {

        var userData = {
            email: req.body.email,
            username: req.body.username,
            password: req.body.password,
        }

        User.create(userData, function (error, user) {
            if (error) {
                return next(error);
            } else {
                req.session.userId = user._id;
                return res.redirect('/profile');
            }
        });

    } else if (req.body.logemail && req.body.logpassword) {
        User.authenticate(req.body.logemail, req.body.logpassword, function (error, user) {
            if (error || !user) {
                var err = new Error('Wrong email or password.');
                err.status = 401;
                return next(err);
            } else {
                req.session.userId = user._id;
                return res.redirect('/profile');
            }
        });
    } else {
        var err = new Error('All fields required.');
        err.status = 400;
        return next(err);
    }
})

function getEmailUser(users, email, pwd) {
    for (let i in users) {
        let u = users[i];
        if (u.email === email && u.password === pwd && u.activated)
            return u
    }
    return undefined;
}

function getPhoneUser(users, phoneNumber) {
    for (let i in users) {
        let u = users[i];
        if (u.mobile === phoneNumber && u.activated)
            return u
    }
    return undefined;
}

function phoneExists(users, mobile) {
    for (let i in users) {
        let u = users[i];
        if (u.mobile === mobile)
            return true
    }
    return false;
}

function phoneFormalize(phoneNum) {
    return phoneNum.replace(/ /g, '')
}

function sendSMS_setSession(phone) {
    //send 4 digits code.
    let phoneNum = "+" + countryCode + phone;
    let randCode = Math.floor(1000 + Math.random() * 9000);
    let msg = 'Your OTP code is ' + randCode + '. Please verify to login in 60 min. Ignore the sms if it is not your phone number.';
    if (!isTest) send_sms.sendSMS(phoneNum, msg, function (err, data) {
        if (err) console.error(err)
        console.debug("Phone number=%s, random code=%s,data=", phoneNum, randCode, data.toString());
    });
    sess[phone] = {
        sms: randCode,
        timestamp: Date.now() + 180000,
    }
    return randCode;
}

/**
 * 根据body参数区分是哪一种操作
 */
router.post('/adminlogin', (req, res) => {
    const rawdata = fs.readFileSync('users.json');
    let users = JSON.parse(rawdata);
    if (isTest) console.log(req.body);
    var i_email = req.body.i_email;
    var i_pwd = req.body.i_pwd;
    if (!i_email || !i_pwd) {
        return res.json({
            errorCode: 1,
            message: 'Please login with email or password',
        })
    }
    var user = getEmailUser(users, i_email, i_pwd);
    if (!user) {
        return res.json({
            errorCode: 1,
            message: "email or passwords dont match",
        })
    }
    req.session.signup = true;
    return res.json({
        errorCode: 0,
        message: "authentication success",
    })
})

router.post('/adminsignup', (req, res) => {
    const rawdata = fs.readFileSync('users.json');
    let users = JSON.parse(rawdata);
    var i_name = req.body.i_name;
    var i_email = req.body.i_email;
    var i_mobile = req.body.i_mobile;
    if (!i_mobile || !i_name) {
        return res.json({
            errorCode: 1,
            message: 'Please key in you name and mobile phone number'
        })
    }
    var user = phoneExists(users, i_mobile);
    if (user) {
        return res.json({
            errorCode: 1,
            message: "user exists"
        })
    }
    users.push({
            "name": i_name,
            "email": i_email,
            "password": "Ectivisecloud@321",
            "mobile": i_mobile,
            "activated": true
        }
    )
    fs.writeFileSync('users.json', JSON.stringify(users));

    // return res.sendFile(path.join(__dirname, './gponcal.html'))

    return res.json({
        errorCode: 0,
        message: 'User created' + i_name
    })

})
router.get('/admin', function (req, res, next) {
    return res.sendFile(path.join(__dirname + '/../admin/admin-login.html'));
});
router.get('/admin/signup', function (req, res, next) {
    if (req.session.signup == true)
        return res.sendFile(path.join(__dirname + '/../admin/admin-signup.html'));
    else
        return res.sendFile(path.join(__dirname + '/../admin/admin-login.html'));
});

router.post('/sendsms', (req, res) => {
    const rawdata = fs.readFileSync('users.json');
    let users = JSON.parse(rawdata);
    console.log(req.body);
    var logmobile = req.body.i_mobile;
    var user = getPhoneUser(users, logmobile);
    if (!user) {
        console.log('user not exists for mobile:' + logmobile);
        return res.json({
            errorCode: 1,
            message: 'Mobile number ' + logmobile + ' not exists, please register or contact Ectivse Cloud admin',
            data: {}
        })
    }
    var sms = sendSMS_setSession(phoneFormalize(req.body.i_mobile));
    var msg = 'Your OTP code has been sent out to your mobile:' + logmobile;// + ". randomCode=" + sms;
    msg = !isTest ? msg : msg + ". randomCode=" + sms;
    return res.json({
        errorCode: 0,
        message: msg,
        data: {
            userCode: user.userCode,
            sms: sms
        }
    })

})

function getUsers() {
    const rawdata = fs.readFileSync('users.json');
    return JSON.parse(rawdata);
}

router.post('/', (req, res) => {
    var logmobile = countryCode + req.body.logmobile;
    var i_otp = req.body.i_otp;
    var mobileLogin = (logmobile && i_otp) ? true : false;
    var emailLogin = (req.body.logemail && req.body.logpassword) ? true : false;

    if (!mobileLogin && !emailLogin)
        return res.send("Please login first");

    if (mobileLogin) {
        var _sess = sess[req.body.logmobile];
        if (!_sess) {
            return res.json({
                errorCode: 1,
                message: "session expired, re-login"
            })
        }

        if (_sess.sms != i_otp) {
            return res.json({
                errorCode: 1,
                message: "mobile phone number(" + req.body.logmobile + ") or sms(" + i_otp + ") incorrect. It should be " + _sess.sms + ". Please return back to the previous login page"
            })
        }
        return res.sendFile(path.join(__dirname, './gponcal.html'))
    } else if (emailLogin) {
        //TODO send verification email to the email address
        let users = getUsers();
        let user = getEmailUser(users, req.body.logemail, req.body.logpassword);
        if (user)
            return res.sendFile(path.join(__dirname, './gponcal.html'))
        else
            return res.send("email or passwords dont match");
    } else {//registration
        return res.send({
            errorCode: 1,
            message: "Cannot register online. Please contact Ectivise Cloud @91550473"
        })
    }
});

// GET for logout logout
router.get('/logout', function (req, res, next) {
    if (req.session) {
        // delete session object
        req.session.destroy(function (err) {
            if (err) {
                return next(err);
            } else {
                return res.redirect('/');
            }
        })
    }
})

module.exports = router;

